package com.atguigu.msm.utils;

import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * 获取随机数
 * 可以使用
 * {@link org.apache.commons.lang3.RandomStringUtils}代替此工具类
 *
 * @author admin
 */
public class RandomUtil {
    static Logger log = LoggerFactory.getLogger(RandomUtil.class);
    private static final Random RANDOM = new Random();

    private static final DecimalFormat FOURDF = new DecimalFormat("0000");

    private static final DecimalFormat SIXDF = new DecimalFormat("000000");

    public static String getFourBitRandom() {
        String s = FOURDF.format(RANDOM.nextInt(10000));
        log.info("4位验证码为:" + s);

        return s;
    }

    public static String getSixBitRandom() {
        String s = SIXDF.format(RANDOM.nextInt(1000000));
        log.info("6位验证码为:" + s);
        return s;
    }

    /**
     * 给定数组，抽取n个数据
     *
     * @param list ?
     * @param n    ?
     * @return ?
     */
    public static ArrayList<Integer> getRandom(List<Integer> list, int n) {

        Random random = new Random();

        HashMap<Object, Object> hashMap = new HashMap<Object, Object>();

        // 生成随机数字并存入HashMap
        for (int i = 0; i < list.size(); i++) {

            int number = random.nextInt(100) + 1;

            hashMap.put(number, i);
        }

        // 从HashMap导入数组
        Object[] robjs = hashMap.values().toArray();
        ArrayList<Integer> r = Lists.newArrayList();
        // 遍历数组并打印数据
        for (int i = 0; i < n; i++) {
            r.add(list.get((int) robjs[i]));
        }
        log.info(r.toString());
        return r;
    }
}
